import os
import time
from datetime import datetime
from webdav3.client import Client


remote_tplink_dir  = "DATA/阿里云盘/luban监控/tplink/"
remote_xiaomi_dir  = "DATA/阿里云盘/luban监控/xiaomi_camera_videos/94F827EF2ABE/"
remote_xiaobai_dir = "DATA/阿里云盘/luban监控/xiaomi_camera_videos/78DF721C1575/"
local_tplink_dir   = "/DATA/sda/tplink/"
local_xiaomi_dir   = "/DATA/sda/xiaomi_camera_videos/94F827EF2ABE/"
local_xiaobai_dir  = "/DATA/sda/xiaomi_camera_videos/78DF721C1575/"


options = {
 'webdav_hostname': "http://127.0.0.1:5244/dav",
 'webdav_login':    "admin",
 'webdav_password': "1234",
 'webdav_timeout': 120
}
client = Client(options)

client.verify = False

# client.mkdir("DATA/baidu/luban监控/tplink")
# client.mkdir("DATA/baidu/luban监控/xiaomi_camera_videos/")
# client.mkdir("DATA/baidu/luban监控/xiaomi_camera_videos/94F827EF2ABE/")
# client.mkdir("DATA/baidu/luban监控/xiaomi_camera_videos/78DF721C1575/")
files1 = client.list("DATA/阿里云盘/luban监控/tplink/")

print(files1)

# client.upload_sync(remote_path="DATA/阿里云盘/luban监控/tplink/2023-10-20", local_path="/DATA/sda/tplink/2023-12-28")

# tplink 摄像头 获取最新文件
# 获取的是一天的文件
def get_tplink_oldest_day_monitoring(dir):
    oldest_file = None
    oldest_date = datetime.max

    for filename in os.listdir(dir):
        if len(filename) == 10 and filename[:4].isdigit() and filename[4] == '-' and filename[5:7].isdigit() and filename[7] == '-' and filename[8:].isdigit():
            file_date = datetime.strptime(filename, '%Y-%m-%d')
            if file_date < oldest_date:
                oldest_date = file_date
                oldest_file = filename

    if oldest_file is None:
        return None

    return os.path.join(dir, oldest_file)

# 小米摄像头 获取最新文件
# 获取的是一小时的文件
def get_xiaomi_oldest_day_monitoring(dir):
    oldest_file = None
    oldest_date = datetime.max

    for filename in os.listdir(dir):
        if len(filename) == 10 and filename.isdigit():
            file_date = datetime.strptime(filename, '%Y%m%d%H')
            if file_date < oldest_date:
                oldest_date = file_date
                oldest_file = filename

    if oldest_file is None:
        return None

    return os.path.join(dir, oldest_file)

# 小白摄像头 获取最新文件
# 获取的是 128MB文件
def get_xiaobai_oldest_day_monitoring(dir):
    oldest_file = None
    oldest_date = datetime.max

    for filename in os.listdir(dir):
        if len(filename) == 33 and filename.endswith('.mp4'):
            file_date_str = filename[:14]
            try:
                file_date = datetime.strptime(file_date_str, '%Y%m%d%H%M%S')
                if file_date < oldest_date:
                    oldest_date = file_date
                    oldest_file = filename
            except ValueError:
                continue

    if oldest_file is None:
        return None

    return os.path.join(dir, oldest_file)


old_file = get_tplink_oldest_day_monitoring(local_tplink_dir)
print("tplink old_file :", old_file)

old_file = get_xiaomi_oldest_day_monitoring(local_xiaomi_dir)
print("xiaomi old_file :", old_file)

old_file = get_xiaobai_oldest_day_monitoring(local_xiaobai_dir)
print("xiaobai old_file:", old_file)


def upload_tplink(dir):
    while True:
        result = os.popen("du -sh " + dir).read().strip()  # 执行 du -sh 命令并获取输出结果
        total_size_str = result.split('\t')[0]  # 截取结果中的容量部分
        total_size = float(total_size_str.replace("G", ""))  # 将容量转换为浮点数
        print("tplink total_size", total_size)

        old_file = get_tplink_oldest_day_monitoring(dir)

        # 本地目录如果大于40G 则继续上传到 网盘
        if total_size > 40:
            local_file = old_file
            remote_file = remote_tplink_dir + os.path.basename(local_file)
            print("tplink uploading file: [", local_file, "] to [", remote_file, "]")
            time.sleep(10)
            client.mkdir(remote_file)
            ret = client.upload_sync(remote_file, local_file)
            if ret == None:
                print("uploading file Success...")
                os.popen("rm -rf " + local_file)
                print("rm file: ", old_file)
            else:
                print("uploading file failed...")
        else:
            return
        time.sleep(10)
        # 暂停 10s



def upload_xiaomi(dir):
    while True:
        result = os.popen("du -sh " + dir).read().strip()  # 执行 du -sh 命令并获取输出结果
        total_size_str = result.split('\t')[0]  # 截取结果中的容量部分
        total_size = float(total_size_str.replace("G", ""))  # 将容量转换为浮点数
        print("xiaomi total_size", total_size)

        old_file = get_xiaomi_oldest_day_monitoring(dir)

        # 本地目录如果大于10G 则继续上传到 网盘
        if total_size > 10:
            local_file = old_file
            remote_file = remote_xiaomi_dir + os.path.basename(local_file)
            print("xiaomi uploading file: [", local_file, "] to [", remote_file, "]")
            time.sleep(10)
            client.mkdir(remote_file)
            ret = client.upload_sync(remote_file, local_file)
            if ret == None:
                print("uploading file Success...")
                os.popen("rm -rf " + local_file)
                print("rm file: ", old_file)
            else:
                print("uploading file failed...")
        else:
            return
        time.sleep(10)
        # 暂停 10s



def upload_xiaobai(dir):
    while True:
        result = os.popen("du -sh " + dir).read().strip()  # 执行 du -sh 命令并获取输出结果
        print("result", result)
        total_size_str = result.split('\t')[0]  # 截取结果中的容量部分
        total_size = float(total_size_str.replace("G", ""))  # 将容量转换为浮点数
        print("xiaobai total_size", total_size)

        old_file = get_xiaobai_oldest_day_monitoring(dir)

        # 本地目录如果大于10G 则继续上传到 网盘
        if total_size > 10:
            local_file = old_file
            remote_file = remote_xiaobai_dir + os.path.basename(local_file)
            print("xiaobai uploading file: [", local_file, "] to [", remote_file, "]")
            time.sleep(10)
            # client.mkdir(remote_file)
            ret = client.upload_sync(remote_file, local_file)
            if ret == None:
                print("uploading file Success...")
                os.popen("rm -rf " + local_file)
                print("rm file: ", old_file)
            else:
                print("uploading file failed...")
        else:
            return
        time.sleep(10)
        # 暂停 10s


upload_tplink(local_tplink_dir)
upload_xiaomi(local_xiaomi_dir)
upload_xiaobai(local_xiaobai_dir)
